package com.wmh.baseservice.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdProfit;
import com.wmh.baseservice.admin.service.AdProfitService;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.LogUtil;
import com.wmh.baseservice.common.utils.QrCodeUtil;
import com.wmh.baseservice.common.wechat.ma.template.WxTemplateMsgUtils;
import com.wmh.baseservice.common.wechat.mp.template.WxSubMsgUtils;
import com.wmh.baseservice.merchant.pojo.MerchantGroupGoods;
import com.wmh.baseservice.merchant.pojo.MerchantIncomeExpend;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.merchant.service.MerchantGroupGoodsService;
import com.wmh.baseservice.merchant.service.MerchantIncomeExpendService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.system.pojo.SysMessage;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysMessageService;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.mapper.UsGroupGoodsOrderMapper;
import com.wmh.baseservice.user.pojo.UsIncomeExpend;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsAddressService;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.wmh.baseservice.user.service.UsIncomeExpendService;
import com.wmh.baseservice.user.service.UsInfoService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wmh generator
 * @since 2022-03-07
 */
@Service
public class UsGroupGoodsOrderServiceImpl extends CommonServiceImpl<UsGroupGoodsOrderMapper, UsGroupGoodsOrder> implements UsGroupGoodsOrderService {

    @Resource
    private UsGroupGoodsOrderMapper usGroupGoodsOrderMapper;
    @Resource
    private MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    private SkdGoodsSpecService merchantSpecService;
    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private AdProfitService adProfitService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantIncomeExpendService merchantIncomeExpendService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private UsIncomeExpendService usIncomeExpendService;
    @Resource
    private UsAddressService usAddressService;


    @Override
    public List<UsGroupGoodsOrder> spellGroupList(Long id) {
        return usGroupGoodsOrderMapper.spellGroupList(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void openGroup(UsGroupGoodsOrder usGroupGoodsOrder, MerchantGroupGoods merchantGroupGoods, SkdGoodsSpec skdGoodsSpec) {
        //减少库存
        if (CommUtil.checkNull(merchantGroupGoods)) {
            if (!merchantGroupGoodsService.updateById(merchantGroupGoods)) {
                throw new ServiceException("修改库存失败");
            }
        } else {
            if (!merchantSpecService.updateById(skdGoodsSpec)) {
                throw new ServiceException("修改规格库存失败");
            }
        }
        //生成带参二维码
        try {
            String qrCode = QrCodeUtil.getQrCodeSave(usGroupGoodsOrder.getOrderNo(), "QrCode", "/pages/shop/offerBulk");
            usGroupGoodsOrder.setQrCode(qrCode);
        } catch (WxErrorException | IOException e) {
            LogUtil.error(e.getMessage());
        }
        //创建订单
        if (usGroupGoodsOrderMapper.insert(usGroupGoodsOrder) != 1) {
            throw new ServiceException("创建订单失败");
        }

    }

    @Override
    public List<UsGroupGoodsOrder> usList(Long teamId) {
        return usGroupGoodsOrderMapper.usList(teamId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void balancePay(UsGroupGoodsOrder usGroupGoodsOrder, BigDecimal payAmount, UsInfo usInfo) {
        //自提二维码
        try {
            if (usGroupGoodsOrder.getType() == 0) {
                JSONObject object = new JSONObject(true);
                object.put("orderNo", usGroupGoodsOrder.getOrderNo());
                object.put("type", "groupGoods");
                String paramsQrCode = QrCodeUtil.createParamsQrCode(object.toJSONString(), "/order/", usGroupGoodsOrder.getOrderNo());
                usGroupGoodsOrder.setQrCode(paramsQrCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //订单修改
        if (!updateById(usGroupGoodsOrder)) {
            throw new ServiceException(usGroupGoodsOrder.toString());
        }
        //用户余额扣减
        usInfo.setBalance(usInfo.getBalance().subtract(payAmount));
        if (!usInfoService.updateById(usInfo)) {
            throw new ServiceException(usInfo.toString());
        }

        //用户支出流水
        UsIncomeExpend usIncomeExpend = new UsIncomeExpend().setStatus(-1).setType(1).setMoney(payAmount)
                .setUsId(usGroupGoodsOrder.getUsId()).setRemark("余额购买团购商品").setOrderNum(usGroupGoodsOrder.getOrderNo());
        if (!usIncomeExpendService.save(usIncomeExpend)) {
            throw new ServiceException(usIncomeExpend.toString());
        }

        //判断是否有上级推广佣金
        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(usGroupGoodsOrder.getGroupGoodsId());
        if (CommUtil.checkNull(merchantGroupGoods.getCommission())) {
            UsInfo us = usInfoService.getByIdForUpdate(usGroupGoodsOrder.getUsId());
            if (CommUtil.checkNull(us) && us.getInviteId() != -1) {
                UsInfo parentInfo = usInfoService.getByIdForUpdate(us.getInviteId());
                //添加用户冻结流水
                UsIncomeExpend freezeIncome = new UsIncomeExpend().setUsId(parentInfo.getId()).setStatus(1).setType(1).setRemark("团购商品佣金").setOrderNum(usGroupGoodsOrder.getOrderNo())
                        .setMoney(merchantGroupGoods.getCommission()).setHasFreeze(-1);
                if (!usIncomeExpendService.save(freezeIncome)) {
                    throw new ServiceException();
                }
            }
        }

        //给商家发送消息
        SysMessage sysMessage = new SysMessage().setMerchantId(usGroupGoodsOrder.getMerchantId()).setTitle("您有一个新的团购商品订单，请到商家后台及时处理")
                .setContent("订单号:" + usGroupGoodsOrder.getOrderNo() + "购买人微信昵称：" + usInfo.getNick());
        UsInfo merchantUs = usInfoService.getOneForUpdate(new QueryWrapper<UsInfo>().eq(UsInfo.MERCHANT_ID, usGroupGoodsOrder.getMerchantId()));
        sysMessage.setUsId(merchantUs.getId());
        if (!sysMessageService.save(sysMessage)) {
            throw new ServiceException();
        }

        if (CommUtil.checkNull(merchantUs,merchantUs.getMpOpenId())){
            //微信公众号发送模板消息
            WxSubMsgUtils.newOrder(merchantUs.getMpOpenId(), "您有一个新的团购商品订单", usGroupGoodsOrder.getPayTime(), "果蔬产品",
                    usInfo.getNick(), usGroupGoodsOrder.getOrderNo(), "请及时进入小程序商家中心-团购管理-订单列表发货处理哦~");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long value) {
        usGroupGoodsOrderMapper.cancelOrder(value);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void theGoods(UsGroupGoodsOrder usGroupGoodsOrder) {
        //判断商家保证金是否大于0,如果不足，那么在，在售后期过时计算收益
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usGroupGoodsOrder.getMerchantId());
        SysParams margin = sysParamsService.getByIdForUpdate(17L);
        if (Integer.parseInt(margin.getValue()) == 1 && merchantInfo.getMargin().compareTo(BigDecimal.ZERO) <= 0) {
            usGroupGoodsOrder.setHasSettlement(-1);
        } else {
            usGroupGoodsOrder.setHasSettlement(1);
            //平台抽成
            SysParams sysParams = sysParamsService.getByIdForUpdate(5L);
            if (!CommUtil.checkNull(sysParams)) {
                throw new ServiceException();
            }
            if (usGroupGoodsOrder.getFreightPrice() == null) {
                usGroupGoodsOrder.setFreightPrice(new BigDecimal(0));
            }
            BigDecimal adMultiply = usGroupGoodsOrder.getRealPrice().subtract(usGroupGoodsOrder.getFreightPrice()).multiply(new BigDecimal(sysParams.getValue()));
            AdProfit adProfit = new AdProfit().setOrigin("团购商品抽成").setMoney(adMultiply);
            if (!adProfitService.save(adProfit)) {
                throw new ServiceException();
            }
            //商家分成
            BigDecimal totalProfit = usGroupGoodsOrder.getRealPrice().subtract(adMultiply);
            if (merchantInfo.getParentId() != -1) {
                //查出所有商家
                List<MerchantInfo> merchantInfos = merchantInfoService.listForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
                merchantInfos.forEach(info -> {
                    BigDecimal profit = totalProfit.multiply(BigDecimal.valueOf(info.getShares()));
                    //添加流水记录
                    MerchantIncomeExpend merchantIncomeExpend = new MerchantIncomeExpend().setMerchantId(info.getId()).setOrderNum(usGroupGoodsOrder.getOrderNo()).setMoney(totalProfit).setRemark("用户收货-团购商品收入").setStatus(1);
                    //商家余额添加
                    info.setBalance(info.getBalance().add(profit));
                    if (!merchantIncomeExpendService.save(merchantIncomeExpend)) {
                        throw new ServiceException();
                    }
                    if (!merchantInfoService.updateById(info)) {
                        throw new ServiceException();
                    }
                });
            } else {
                //添加流水记录
                MerchantIncomeExpend merchantIncomeExpend = new MerchantIncomeExpend().setMerchantId(merchantInfo.getId()).setOrderNum(usGroupGoodsOrder.getOrderNo()).setMoney(totalProfit).setRemark("用户收货-团购商品收入").setStatus(1);
                //商家余额添加
                merchantInfo.setBalance(merchantInfo.getBalance().add(totalProfit));
                if (!merchantIncomeExpendService.save(merchantIncomeExpend)) {
                    throw new ServiceException();
                }
                if (!merchantInfoService.updateById(merchantInfo)) {
                    throw new ServiceException();
                }
            }
        }
        //修改订单状态
        if (!updateById(usGroupGoodsOrder)) {
            throw new ServiceException();
        }
    }

    @Override
    public int totalCount(Map<String, Object> map) {
        return usGroupGoodsOrderMapper.totalCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void openOrJoinGroup(MerchantGroupGoods merchantGroupGoods, SkdGoodsSpec skdGoodsSpec, UsGroupGoodsOrder usGroupGoodsOrder) {
        //库存扣减
        if (CommUtil.checkNull(skdGoodsSpec)) {
            if (!merchantSpecService.updateById(skdGoodsSpec)) {
                throw new ServiceException(skdGoodsSpec.toString());
            }
        }
        if (!merchantGroupGoodsService.updateById(merchantGroupGoods)) {
            throw new ServiceException(merchantGroupGoods.toString());
        }
        //提交订单
        if (!save(usGroupGoodsOrder)) {
            throw new ServiceException(usGroupGoodsOrder.toString());
        }
    }


    @Override
    public List<UsGroupGoodsOrder> settlementOrderList(Long id) {
        return usGroupGoodsOrderMapper.settlementOrderList(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void weChatPay(String orderNum) {
        UsGroupGoodsOrder usGroupGoodsOrder = getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        //修改支付类型
        usGroupGoodsOrder.setPayType(2);
        usGroupGoodsOrder.setPayTime(new Date());
        //自提二维码
        try {
            if (usGroupGoodsOrder.getType() == 0) {
                JSONObject object = new JSONObject(true);
                object.put("orderNum", usGroupGoodsOrder.getOrderNo());
                object.put("type", "groupGoods");
                String paramsQrCode = QrCodeUtil.createParamsQrCode(object.toJSONString(), "/order/", usGroupGoodsOrder.getOrderNo());
                usGroupGoodsOrder.setQrCode(paramsQrCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //订单修改
        if (usGroupGoodsOrder.getType() == 1 || usGroupGoodsOrder.getType() == 3) {
            usGroupGoodsOrder.setStatus(1);
        } else {
            usGroupGoodsOrder.setStatus(3);
        }
        if (!updateById(usGroupGoodsOrder)) {
            throw new ServiceException(usGroupGoodsOrder.toString());
        }
        //用户支出流水
        BigDecimal payAmount;
        if (CommUtil.checkNull(usGroupGoodsOrder.getFreightPrice())) {
            payAmount = usGroupGoodsOrder.getRealPrice().add(usGroupGoodsOrder.getFreightPrice());
        } else {
            payAmount = usGroupGoodsOrder.getRealPrice();
        }
        UsIncomeExpend usIncomeExpend = new UsIncomeExpend().setStatus(-1).setType(1).setMoney(payAmount)
                .setUsId(usGroupGoodsOrder.getUsId()).setRemark("微信支付购买团购商品").setOrderNum(usGroupGoodsOrder.getOrderNo());
        if (!usIncomeExpendService.save(usIncomeExpend)) {
            throw new ServiceException(usIncomeExpend.toString());
        }
        //判断是否有上级推广佣金
        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(usGroupGoodsOrder.getGroupGoodsId());
        if (CommUtil.checkNull(merchantGroupGoods.getCommission())) {
            UsInfo usInfo = usInfoService.getByIdForUpdate(usGroupGoodsOrder.getUsId());
            if (CommUtil.checkNull(usInfo) && usInfo.getInviteId() != -1) {
                UsInfo parentInfo = usInfoService.getByIdForUpdate(usInfo.getInviteId());
                //添加用户冻结流水
                UsIncomeExpend freezeIncome = new UsIncomeExpend().setUsId(parentInfo.getId()).setStatus(1).setType(1).setRemark("团购商品佣金").setOrderNum(usGroupGoodsOrder.getOrderNo())
                        .setMoney(merchantGroupGoods.getCommission()).setHasFreeze(-1);
                if (!usIncomeExpendService.save(freezeIncome)) {
                    throw new ServiceException();
                }
            }
        }

        //给商家发送消息
        UsInfo usInfo = usInfoService.getByIdForUpdate(usGroupGoodsOrder.getUsId());
        SysMessage sysMessage = new SysMessage().setMerchantId(usGroupGoodsOrder.getMerchantId()).setTitle("您有一个新的团购商品订单，请到商家后台及时处理")
                .setContent("订单号:" + usGroupGoodsOrder.getOrderNo() + "购买人微信昵称：" + usInfo.getNick());
        UsInfo merchantUs = usInfoService.getOneForUpdate(new QueryWrapper<UsInfo>().eq(UsInfo.MERCHANT_ID, usGroupGoodsOrder.getMerchantId()));
        sysMessage.setUsId(merchantUs.getId());
        if (!sysMessageService.save(sysMessage)) {
            throw new ServiceException();
        }

        if (CommUtil.checkNull(merchantUs,merchantUs.getMpOpenId())){
            //微信公众号发送模板消息
            WxSubMsgUtils.newOrder(merchantUs.getMpOpenId(), "您有一个新的团购商品订单", usGroupGoodsOrder.getPayTime(), "果蔬产品",
                    usInfo.getNick(), usGroupGoodsOrder.getOrderNo(), "请及时进入小程序商家中心-团购管理-订单列表发货处理哦~");
        }

    }

    @Override
    public List<Long> thyDayUsAvatar(Long id, Integer batchNum) {
        return usGroupGoodsOrderMapper.thyDayUsAvatar(id, batchNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delivery(UsGroupGoodsOrder usGroupGoodsOrder) {
        if (!updateById(usGroupGoodsOrder)) {
            throw new ServiceException();
        }
        SysMessage sysMessage = new SysMessage().setUsId(usGroupGoodsOrder.getUsId()).setTitle("您的订单已发货").setContent("您订单号为:" + usGroupGoodsOrder.getOrderNo() + "的商品已发货").setStatus(0);
        if (!sysMessageService.save(sysMessage)) {
            throw new ServiceException();
        }

        //发送模板消息
        JSONObject object = new JSONObject(true);
        JSONObject parseObject = JSONObject.parseObject(usGroupGoodsOrder.getSnapshot());
        String title = parseObject.getString("title");
        if (title.length() > 20) {
            title = title.substring(0, 20);
        }
        object.put("thing2", title);
        UsAddress usAddress = usAddressService.getByIdForUpdate(usGroupGoodsOrder.getAddressId());
        object.put("name3", usAddress.getName());
        object.put("thing4", usAddress.getProvince() + usAddress.getCity() + usAddress.getArea());
        if (usGroupGoodsOrder.getType() == 1) {
            object.put("thing5", "快递运送");
            object.put("thing12", usGroupGoodsOrder.getExpressNumber());
        } else {
            object.put("thing5", "专人配送");
            object.put("thing12", "您的快递会有专人联系您进行上门配送哦~");
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usGroupGoodsOrder.getUsId());
        //订阅消息提醒
        WxTemplateMsgUtils.noticeUserDelivery(usInfo.getOpenId(), object);
        //关注公众号模板消息提醒
        if (CommUtil.checkNull(usInfo.getMpOpenId())) {
            MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService
                    .getById(usGroupGoodsOrder.getGroupGoodsId());
            if (CommUtil.checkNull(merchantGroupGoods)) {
                if (CommUtil.checkNull(usGroupGoodsOrder.getExpressNumber())) {
                    WxSubMsgUtils.delivery(usInfo.getMpOpenId(), "尊敬的用户您好，您购买的拼单商品已发货",
                            merchantGroupGoods.getTitle(), usGroupGoodsOrder.getOrderNo(), "快递寄送",
                            usGroupGoodsOrder.getExpressNumber(), usAddress.getAddress(), "请关注物流信息");
                } else {
                    WxSubMsgUtils.delivery(usInfo.getMpOpenId(), "尊敬的用户您好，您的团购商品已准备完毕，快递会有专人联系您进行上门配送哦",
                            merchantGroupGoods.getTitle(), usGroupGoodsOrder.getOrderNo(), "专人配送",
                            "专人配送", usAddress.getAddress(), "请注意接收电话");
                }
            }
        }
    }

    @Override
    public List<UsGroupGoodsOrder> getSettleTheCommissionOrderList(String day) {
        return usGroupGoodsOrderMapper.getSettleTheCommissionOrderList(day);
    }

    @Override
    public List<UsGroupGoodsOrder> getCanSettleEarningsOrderList(String day) {
        return usGroupGoodsOrderMapper.getCanSettleEarningsOrderList(day);
    }

    @Override
    public List<UsGroupGoodsOrder> autoDeliver(String value) {
        return usGroupGoodsOrderMapper.autoDeliver(value);
    }

    @Override
    public BigDecimal promoteCommission(List<Long> merchantIds) {
        return usGroupGoodsOrderMapper.promoteCommission(merchantIds);
    }

    @Override
    public int queryShortOrder(Long usId) {
        return usGroupGoodsOrderMapper.queryShortOrder(usId);
    }

    /**
     * 根据订单类型和关键字过滤订单列表
     * @param usId 用户id
     * @param type 订单类型
     * @param keyword 关键字
     * @return 返回过滤后的订单
     */
    @Override
    public List<UsGroupGoodsOrder> getFilteredOrders(Long usId, Integer type, String keyword) {
        QueryWrapper<UsGroupGoodsOrder> usGroupGoodsOrderQueryWrapper = new QueryWrapper<>();
        usGroupGoodsOrderQueryWrapper.eq("us_id", usId);

        // 如果关键字不为空，则添加关联查询
        if (keyword != null && !keyword.isEmpty()) {
            // 添加对merchant_group_goods表的关联查询
            usGroupGoodsOrderQueryWrapper.and(wrapper ->
                    wrapper.exists(
                            "SELECT 1 FROM merchant_group_goods " +
                                    "WHERE merchant_group_goods.id = us_group_goods_order.group_goods_id " +
                                    "AND merchant_group_goods.title LIKE '%" + keyword + "%'"
                    )
            );
        }

        // 获取当前用户所有订单
        List<UsGroupGoodsOrder> allOrders = usGroupGoodsOrderMapper.selectList(usGroupGoodsOrderQueryWrapper);

        // 过滤订单列表
        return allOrders.stream()
                .filter(order -> isTypeMatch(order, type)) // 根据type过滤
                .collect(Collectors.toList());
    }

    private boolean isTypeMatch(UsGroupGoodsOrder order, Integer type) {
        if (type == null) {
            return true; // 如果type为null, 表示不过滤, 返回所有订单
        }

        // 根据type值过滤订单
        switch (type) {
            case 0:
                return order.getStatus().equals(0); // 待支付订单
            case 1:
                return Arrays.asList(1, 2, 3, 4).contains(order.getStatus()); // 发货订单 (包括待发货, 待收货, 待提货, 已提货)
            case -2:
                return !order.getAfterSaleStatus().equals(0); // 售后订单 (0:未申请售后 1:申请退款中 2:退款完成)
            default:
                return false;
        }
    }

    /**
     * 根据团长团号列表查询团长订单总数
     * @param groupNoList 团长团号列表
     * @return 订单总数
     */
    @Override
    public int getLeaderTotalOrderNumByGroupNoList(List<Long> groupNoList) {
        if (groupNoList == null || groupNoList.isEmpty()) {
            return 0;
        }
        QueryWrapper<UsGroupGoodsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("group_no", groupNoList);
        return usGroupGoodsOrderMapper.selectCount(queryWrapper);
    }
}
